package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取本次请求路径
        String resultURI = request.getRequestURI();
        log.info("拦截到请求：{}", request.getRequestURI());
        String urls[] = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //2.判断本次请求是否需要处理
        boolean check = check(urls, resultURI);
        //3.如果不需要处理，直接放行
        if (check) {
            filterChain.doFilter(request, response);
            log.info("该请求不需要处理，直接放行！");
            return;
        }
        //4.1判断用户是否登录，如果登录，直接放行
        if (request.getSession().getAttribute("employee") != null) {
            Long empid = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empid);
            filterChain.doFilter(request, response);
            log.info("用户已登录，该请求放行！");
            return;
        }
        //4.2判断用户是否登录，如果登录，直接放行
        if (request.getSession().getAttribute("user") != null) {
            Long useid = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(useid);
            filterChain.doFilter(request, response);
            log.info("用户已登录，该请求放行！");
            return;
        }
        //5.如果未登录，通过JSON输出流向客户端返回未登录结果
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        log.info("用户未登录，拦截请求返回未登录！");
        return;

    }

    public boolean check(String[] urls, String resultURI) {
        log.info("遍历请求，是否为不需要处理的请求！");
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, resultURI);
            if (match) {
                return true;
            }
        }
        return false;
    }

}
